package cn.kgm.makeGod.action;

import cn.kgm.makeGod.Character;
import cn.kgm.makeGod.Relationship;
import cn.kgm.makeGod.RelationshipType;
import cn.kgm.makeGod.condition.EventResult;
import cn.kgm.makeGod.condition.WorldState;
import lombok.Builder;
import lombok.Data;

import java.util.Random;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-11 14:29
 * @Description: cn.kgm.makeGod.action.StartBattleAction
 */
@Data
@Builder
public class StartBattleAction implements Action {

    private boolean lethal;

    public StartBattleAction() {
    }

    public StartBattleAction(boolean lethal) {
        this.lethal = lethal;
    }

    @Override
    public void execute(Character actor, Character target, WorldState world, EventResult result) {
        result.addLog(actor.getName() + " 向 " + target.getName() + " 发起了" + (lethal ? "生死" : "切磋") + "战斗!");

        // 简化的战斗逻辑
        int actorPower = actor.getLevel() * 10 + actor.getAttack();
        int targetPower = target.getLevel() * 10 + target.getDefense();

        Random random = new Random();
        // 加入运气因素
        actorPower += random.nextInt(actor.getLuck());
        targetPower += random.nextInt(target.getLuck());

        if (actorPower > targetPower) {
            result.addLog(actor.getName() + " 战胜了 " + target.getName());

            if (lethal) {
                // 处理死亡
                world.removeCharacter(target);
                result.addLog(target.getName() + " 不幸陨落!");

                // 通知所有与目标有关系的人
                for (Character character : world.getCharacters().values()) {
                    Relationship rel = character.getRelationshipTo(target.getId());
                    if (rel != null && rel.getValue() > 0) {
                        result.addLog(character.getName() + " 得知 " + target.getName() + " 的死讯，悲痛欲绝");
                        // 降低与凶手的关系
                        Relationship toActor = character.getRelationshipTo(actor.getId());
                        if (toActor != null) {
                            toActor.setValue(toActor.getValue() - 30);
                        } else {
                            character.addRelationship(new Relationship(
                                    character.getId(), actor.getId(),
                                    RelationshipType.SWORN_ENEMY, -30
                            ));
                        }
                    }
                }
            }

            // 胜者获得战利品
            result.addLog(actor.getName() + " 获得了胜利的喜悦，修为略有提升");
            actor.setLevel(actor.getLevel() + 1);

        } else {
            result.addLog(target.getName() + " 抵御了 " + actor.getName() + " 的攻击");
            // 败者关系恶化
            Relationship rel = actor.getRelationshipTo(target.getId());
            if (rel != null) {
                rel.setValue(rel.getValue() - 10);
            }
        }
    }

}
